package com.powervision.mvvmdemo.ui.activity

import android.text.Editable
import android.text.TextWatcher
import android.widget.Toast
import androidx.activity.viewModels
import by.kirich1409.viewbindingdelegate.viewBinding
import com.powervision.base.base.BaseActivity
import com.powervision.base.util.LogUtils
import com.powervision.base.util.ToastUtils
import com.powervision.http.SHOW_TOAST
import com.powervision.mvvmdemo.R
import com.powervision.mvvmdemo.databinding.ActivityLoginBinding
import com.powervision.mvvmdemo.ui.viewmodel.LoginViewModel

/**
 * @auth: njb
 * @date: 2021/12/13 13:55
 * @desc: 用户登录
 */
class LoginActivity : BaseActivity(R.layout.activity_login) {
    private val mBinding by viewBinding(ActivityLoginBinding::bind)
    private val mViewModel by viewModels<LoginViewModel>()
    private var username: String ?= null
    private var password: String ?= null

    override fun init() {
        initData()
        initObserver()
    }

    private fun initObserver() {
        mViewModel.userLiveData.observeState(this) {
            onSuccess {
                LogUtils.d("--userInfo--",it.toString())
                ToastUtils.shortToast("登录成功")
            }
            onException {
                LogUtils.e("--error--",it.message.toString())
                ToastUtils.shortToast("登录失败")}
        }
    }

    private fun initData() {
        mBinding.etUserName.addTextChangedListener(object :TextWatcher{
            override fun beforeTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) {

            }

            override fun onTextChanged(s: CharSequence?, p1: Int, p2: Int, p3: Int) {
                username = s.toString().trim()
            }

            override fun afterTextChanged(p0: Editable?) {

            }

        })
        mBinding.etPassWord.addTextChangedListener(object :TextWatcher{
            override fun beforeTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) {

            }

            override fun onTextChanged(s: CharSequence?, p1: Int, p2: Int, p3: Int) {
                password = s.toString().trim()
            }

            override fun afterTextChanged(p0: Editable?) {

            }

        })
        mBinding.btnLogin.setOnClickListener {
            mViewModel.login(username = username!!, password = password!!)
        }
    }

}